#!/usr/bin/env sh

# 选择或输入 Redis 镜像
Redis_Image_Selection()
{
  while [ -z "${REDIS_IMAGE}" ]; do
    Echo_Blue "选择 Redis 镜像(${#REDIS_IMAGES[*]}):"

    # for image in ${REDIS_IMAGES[*]}
    for ((i=0;i<${#REDIS_IMAGES[*]};i++))
    do
      echo "${i}) ${REDIS_IMAGES[i]}"
    done

    read -p "请选择镜像序号, 或输入镜像名称: " REDIS_IMAGE
    echo

    if [[ ${REDIS_IMAGE} =~ ^[0-9]+$ ]]; then
      REDIS_IMAGE=${REDIS_IMAGES[${REDIS_IMAGE}]}
    fi
  done

  # 数据库配置
  Redis_Config
}

# 数据库配置
Redis_Config()
{
  Echo_Green "Redis 配置:"
  echo "REDIS_IMAGE=${REDIS_IMAGE}"

  # 包名:版本号
  image=${REDIS_IMAGE%%-*}
  repository=${image%:*}
  version=${image#*:}

  # 资源路径
  REDIS_PATH=${DATA_PATH}/${repository}/${version}

  echo "REDIS_HOST=redis"

  # REDIS_PORT=6379
  if [ -z "${REDIS_PORT}" ]; then
    CACHE=6379
    read -p "数据库端口(default=${CACHE}): " REDIS_PORT
  else
    echo "REDIS_PORT=${REDIS_PORT}"
  fi
  if [ -z "${REDIS_PORT}" ]; then
    REDIS_PORT=${CACHE}
  fi
  # 检查端口占用情况
  Check_Port ${REDIS_PORT}
  if [ ! -z "${ERROR}" ]; then
    Exit_Confirm
  fi

  # REDIS_PASSWORD
  if [ -z "${REDIS_PASSWORD}" ]; then
    CACHE=""
    read -p "数据库密码(default=${CACHE}): " REDIS_PASSWORD
  else
    echo "REDIS_PASSWORD=${REDIS_PASSWORD}"
  fi
  if [ -z "${REDIS_PASSWORD}" ]; then
    REDIS_PASSWORD=${CACHE}
  fi

  # 确认配置
  Redis_Config_Confirm
}

# 确认配置
Redis_Config_Confirm()
{
  confirm="y"
  read -p "确认配置Y/n: " confirm
  if [[ -z "${confirm}" || "${confirm}" == "y" ]]; then
    # 保存全局安装配置
    Redis_Config_Update
    Echo_Green "配置已保存！"
    echo
  else
    # 重置
    REDIS_IMAGE=
    REDIS_PATH=
    REDIS_PORT=
    REDIS_PASSWORD=
    echo
    Redis_Image_Selection
  fi
}

# 更新数据库配置
Redis_Config_Update()
{
  # install.conf
  sed -i -e "s|REDIS_IMAGE=.*|REDIS_IMAGE=${REDIS_IMAGE}|g;" ${INSTALL_CONF}
  sed -i -e "s|REDIS_PATH=.*|REDIS_PATH=${REDIS_PATH}|g;" ${INSTALL_CONF}
  sed -i -e "s|REDIS_PORT=.*|REDIS_PORT=${REDIS_PORT}|g;" ${INSTALL_CONF}
  sed -i -e "s|REDIS_PASSWORD=.*|REDIS_PASSWORD=${REDIS_PASSWORD}|g;" ${INSTALL_CONF}

  # docker-compose.yml
  sed -i -e "s|REDIS_IMAGE|${REDIS_IMAGE}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|REDIS_PATH|${REDIS_PATH}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|REDIS_PORT|${REDIS_PORT}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|REDIS_PASSWORD|${REDIS_PASSWORD}|g;" ${DOCKER_COMPOSE_YML}

  # Dockerfile
}